package xuperchain

import (
	"encoding/json"
	"fmt"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

func IsUserAuthorized(papername string, username string) (result string) {

	type AuthorizationResponse struct {
		IsAuthorized string `json:"0"`
	}

	account, err := account.GetAccountFromFile(path, pwd)
	if err != nil {
		fmt.Printf("GetAccountFromFile err: %v\n", err)
		return
	}
	fmt.Printf("privatekey Account address: %v\n", account.Address)

	err = account.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	xchainClient, err := xuper.New(nodeAddress)
	if err != nil {
		panic(err)
	}
	contractName := "xc_filestorage8"
	// 测试检查用户是否被授权
	argsIsUserAuthorized := map[string]string{
		"_name":     papername,
		"_username": username,
	}

	txIsUserAuthorized, err := xchainClient.QueryEVMContract(account, contractName, "isUserAuthorized", argsIsUserAuthorized)
	if err != nil {
		panic(err)
	}
	var authResponses []AuthorizationResponse
	err = json.Unmarshal([]byte(txIsUserAuthorized.ContractResponse.Body), &authResponses)
	if err != nil {
		panic(err)
	}
	if len(authResponses) > 0 {
		return authResponses[0].IsAuthorized
	}
	return "false"
}
